package com.lonely.goods.service.impl;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lonely.common.core.domain.BaseEntity;
import com.lonely.common.utils.SecurityUtils;
import com.lonely.goods.domain.dto.material.MaterialItemPageQueryDTO;
import com.lonely.goods.domain.entity.SysMaterialItem;
import com.lonely.goods.domain.vo.material.items.MaterialItemPageVO;
import com.lonely.goods.domain.vo.material.items.MaterialItemVO;
import com.lonely.goods.domain.vo.material.page.MaterialItemDetailVO;
import com.lonely.goods.mapper.SysMaterialItemMapper;
import com.lonely.goods.service.IMaterialItemService;
import com.lonely.order.utils.GeneratorUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * @author : 黄志标
 * @date: 2025/7/10 10:05
 * @description: 物料明细服务实现类
 */
@Service
public class MaterialItemServiceImpl extends ServiceImpl<SysMaterialItemMapper, SysMaterialItem> implements IMaterialItemService {

    /**
     * 查询物料
     *
     * @param queryDto
     * @return
     */
    @Override
    public Page<MaterialItemPageVO> queryMaterialItemPage(MaterialItemPageQueryDTO queryDto) {
        Page<MaterialItemPageVO> page = new Page<>(queryDto.getCurrent(), queryDto.getSize());
        page = super.getBaseMapper().page(page, queryDto);
        return page;
    }

    /**
     * 提交物料明细
     *
     * @param materialId
     * @param materialItemDetails
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void submitMaterialItems(Long materialId, List<MaterialItemDetailVO> materialItemDetails) {

        if (CollUtil.isEmpty(materialItemDetails)) {
            return;
        }
        Map<Long, MaterialItemDetailVO> submitItemMap = materialItemDetails.stream().filter(x -> x.getId() != null).collect(Collectors.toMap(MaterialItemDetailVO::getId, Function.identity()));
        List<Long> submitItemIds = materialItemDetails.stream().map(MaterialItemDetailVO::getId).filter(Objects::nonNull).collect(Collectors.toList());

        // 数据库中已存在的物料明细数据
        List<SysMaterialItem> materialItems = super.list(new LambdaQueryWrapper<SysMaterialItem>()
                .eq(SysMaterialItem::getMaterialId, materialId)
        );
        List<Long> existsMaterialItemIds = materialItems.stream().map(BaseEntity::getId).collect(Collectors.toList());


        // 获取待新增的数据
        List<MaterialItemDetailVO> needAddItemDetails = materialItemDetails.stream().filter(x -> x.getId() == null).collect(Collectors.toList());

        // 获取待删除的数据
        List<Long> needRemoveItemIds = existsMaterialItemIds.stream().filter(x -> !submitItemIds.contains(x)).collect(Collectors.toList());

        // 获取待更新的数据
        List<Long> needUpdateItemIds = existsMaterialItemIds.stream().filter(submitItemIds::contains).collect(Collectors.toList());

        // 入库
        if (CollUtil.isNotEmpty(needAddItemDetails)) {
            List<SysMaterialItem> needAddItems = needAddItemDetails.stream().map(x -> {
                SysMaterialItem sysMaterialItem = new SysMaterialItem();
                BeanUtils.copyProperties(x, sysMaterialItem);
                sysMaterialItem.setMaterialId(materialId);
                sysMaterialItem.setSku(GeneratorUtil.generatorMaterialItemSku());
                sysMaterialItem.setCreateBy(SecurityUtils.getUserId());
                sysMaterialItem.setUpdateBy(SecurityUtils.getUserId());
                return sysMaterialItem;
            }).collect(Collectors.toList());
            super.saveBatch(needAddItems);
        }

        if (CollUtil.isNotEmpty(needRemoveItemIds)) {
            super.removeByIds(needRemoveItemIds);
        }

        if (CollUtil.isNotEmpty(needUpdateItemIds)) {
            List<SysMaterialItem> needUpdateItems = materialItems.stream().filter(x -> needUpdateItemIds.contains(x.getId()))
                    .peek(x -> {
                        MaterialItemDetailVO submitItem = submitItemMap.get(x.getId());
                        BeanUtils.copyProperties(submitItem, x);
                    }).collect(Collectors.toList());
            super.updateBatchById(needUpdateItems);
        }
    }

    /**
     * 获取指定物料明细id对应的物料明细信息
     *
     * @param materialItemId
     * @return
     */
    @Override
    public MaterialItemVO getMaterialItemDetail(Long materialItemId) {
        return super.getBaseMapper().getMaterialItemDetailById(materialItemId);
    }

    /**
     * 批量获取指定物料明细id对应的物料信息
     *
     * @param materialItemIds
     * @return
     */
    @Override
    public List<MaterialItemVO> queryMaterialInfoByIds(List<Long> materialItemIds) {
        if (CollUtil.isEmpty(materialItemIds)) {
            return new ArrayList<>();
        }
        return super.getBaseMapper().batchQueryMaterialItemDetailByIds(materialItemIds);
    }
}
